package com.lky.marshall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.lky.common.to.es.SkuEsModle;
import com.lky.marshall.search.config.MarshallElasticSearchConfig;
import com.lky.marshall.search.constant.EsConstant;
import com.lky.marshall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by
 * autor : Marshall lky
 * datetime: 2021/3/26 16:32
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService
{
    @Autowired
    RestHighLevelClient highLevelClient;

    @Override
    public Boolean productStatusUp(List<SkuEsModle> skuEsModles) throws IOException {
        //将数据保存到es中.
        //1.给es中建立索引,product
        //2.给es中保存数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModle skuEsModle : skuEsModles) {
            //构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModle.getSkuId().toString());
            String s = JSON.toJSONString(skuEsModle);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = highLevelClient.bulk(bulkRequest, MarshallElasticSearchConfig.COMMON_OPTIONS);
        //TODO 批量处理错误
        boolean b = bulk.hasFailures();
        if (b){
            List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            log.error("商品商家错误:{}"+collect);
        }
        return b;
    }
}
